﻿/// <reference path="../../../Proggy/Scripts/jquery-1.7.2-vsdoc.js" />
/// <reference path="../../../Proggy/Content/Scripts/ProggyCore.js" />
/// <reference path="Proggy.CorePropertyTypes.js" />
/// <reference path="../ThirdParty/tiny_mce/jquery.tinymce.js" />
/// <reference path="../ThirdParty/tiny_mce/tiny_mce_src.js" />
/// <reference path="../../../Proggy/Content/Scripts/Proggy_Content_Edit.js" />
/// <reference path="Proggy.CorePropertyTypes.DragAndDrop.js" />



// object
Proggy.CorePropertyTypes.Rte = function () {

    // variables
    var theEditor;
    var idOfContentPicker;
    var idOfImagePicker;

    // replace dangerous content
    var replaceDangerousContent = function (content) {

        //
        content = content.replace(/&#39/g, "&apos");

        //
        return content;

    };

    // custom link button final function
    var linkButtonFinalFunction = function () {

        // get final item 
        var lnkFinalItem = jQuery(".ui-dialog:last").find("a.us-autorendered:first");

        // check
        if (lnkFinalItem.size() == 1) {

            // set vars
            var lnkCurrentNode = window.RTE_LNK_CURRENT_NODE;
            var lnkEd = tinyMCE.activeEditor;
            var lnkAlreadyLinked = window.RTE_LNK_ALREADY_LINKED;
            var lnkLb = window.RTE_LNK_LB;

            // remove class
            lnkFinalItem.removeAttr("class");

            // check if link exists
            if (lnkAlreadyLinked) {

                // replace
                lnkCurrentNode.replaceWith(lnkFinalItem);
            }
            else {

                //create link
                lnkEd.execCommand("insertHTML", false, lnkFinalItem[0].outerHTML);
            }

            // kill dialog
            lnkLb.dialog("close");
        };

    };

    // custom link button
    var getCustomLinkButtonConfig = function (ed) {

        // get title
        var theTitle = "Link";

        // get on click
        var theOnClick = function (evt) {

            // so here

            // focus
            ed.focus();

            // get range
            var range = ed.selection.getRng();

            // get node
            var node = ed.selection.getNode();

            /**********/

            var nodesOk = true;
            var parentTag = node.nodeName.toLowerCase();
            var parentNode;
            var currentNode = jQuery(node);

            // set node
            try {

                // loop
                while (parentTag == undefined && parentNode == undefined || (parentTag != "a" && parentTag != "body")) {



                    parentNode = currentNode.parent();
                    //console.log(parentNode);

                    parentTag = parentNode.prop("tagName").toLowerCase();
                    //console.log(parentTag);

                    currentNode = parentNode;
                    //console.log(currentNode);

                }
            }
            catch (err) {
                nodesOk = false;
            }

            // get already linked
            var alreadyLinked = parentTag == "a"

            // get ok
            var ok =
                    nodesOk && (

                        (range.collapsed && alreadyLinked)
                        ||
                        (!range.collapsed)

                    );

            // create link
            var urlPickerLink =
                window.ROOT_URL +
                "ProggyCore/Rte/LinkCreatorEditor" +
                "?text=" + (alreadyLinked ? currentNode.html() : ed.selection.getContent()) +
                "&href=" + (alreadyLinked ? currentNode.attr("href") : "") +
                "&title=" + (alreadyLinked ? currentNode.attr("title") : "");


            // go
            if (ok) {

                // create dummy link stuff
                var dummyLink = jQuery("<a href=\"" + urlPickerLink + "\" />");
                var dummyE = {
                    preventDefault: function () {

                    }
                };

                // set variables
                window.RTE_LNK_ALREADY_LINKED = alreadyLinked;
                window.RTE_LNK_CURRENT_NODE = currentNode;

                // load content picker
                Proggy.Static.InitialLoadIntoLightbox(dummyLink, dummyE, function (lb, lbInner) {

                    // set lb
                    window.RTE_LNK_LB = lb;

                    // now "before show" function will run when required


                });
            }
        };

        //
        return {
            title: theTitle,
            onclick: theOnClick
        };

    };

    // custom setup
    var getMceSetup = function (ed) {

        // link button
        ed.addButton("link", getCustomLinkButtonConfig(ed));

        // save
        ed.onSaveContent.add(function (i, o) {

            //
            o.content = replaceDangerousContent(o.content);            

        });

    };

    // on init setup
    var getInitInstance = function (inst) {

        // After instance created
        inst.execCommand("mceCleanup", false);
    };

    // on remove
    var getRemoveInstance = function (inst) {

    }

    // bind text area
    var bindTextAreaAsRte = function (idOfTextArea, configObjectText) {

        //
        var finalConfigText = "";

        // get text area
        var theTextArea = jQuery("#" + idOfTextArea);

        // create config object
        var configObject = jQuery.parseJSON(configObjectText);

        // add link button
        configObject.setup = getMceSetup;

        // add oninstancecreated
        configObject.init_instance_callback = getInitInstance;
        configObject.remove_instance_callback = getRemoveInstance;
        configObject.paste_auto_cleanup_on_paste = true;
        configObject.plugins = configObject.plugins + ",paste";



        // init
        theTextArea.tinymce(configObject);
    };

    // init
    this.Init = function (idOfTextArea, configObjectText) {

        // set vars
        idOfContentPicker = idOfTextArea + "_cp";
        idOfImagePicker = idOfImagePicker + "_ip";

        // bind text area
        bindTextAreaAsRte(idOfTextArea, configObjectText);

        // check for final link
        Proggy.Static.AddToBeforeLightboxContentShowMethods(linkButtonFinalFunction);

        // add to drag and drop update
        Proggy.CorePropertyTypes.Static.DragAndDrop.AddToBeforeUpdateMethods(function () {

            // check editor
            if (tinyMCE != undefined && tinyMCE.activeEditor != undefined) {

                // remove
                tinyMCE.activeEditor.remove();

                // get text area
                var textarea = jQuery("#" + idOfTextArea);

                // check
                if (textarea.size() == 1) {

                    // hide
                    textarea.hide();
                }
            }

        });
    };

};